package com.cnswhy.cloud.server.system.controller;

import com.cnswhy.cloud.common.core.base.R;
import com.cnswhy.cloud.common.core.base.controller.SuperController;
import com.cnswhy.cloud.common.core.entity.constant.CnswhyConstant;
import com.cnswhy.cloud.server.system.dto.MenuPageDTO;
import com.cnswhy.cloud.server.system.dto.MenuSaveDTO;
import com.cnswhy.cloud.server.system.dto.MenuUpdateDTO;
import com.cnswhy.cloud.server.system.entity.Menu;
import com.cnswhy.cloud.server.system.entity.VueRouter;
import com.cnswhy.cloud.server.system.service.MenuService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//import com.github.zuihou.security.annotation.PreAuth;


/**
 * <p>
 * 前端控制器
 * 菜单表
 * </p>
 *
 * @author cnswhy
 * @date 2020-10-08
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/menu")
@Api(value = "Menu", tags = "菜单表")
//@PreAuth(replace = "menu:")
public class MenuController extends SuperController<MenuService, Long, Menu, MenuPageDTO, MenuSaveDTO, MenuUpdateDTO> {
    @GetMapping("/getUserRouters/{username}")
    public R<Object> getUserRouters(@NotBlank(message = "{required}") @PathVariable String username) {
        Map<String, Object> result = new HashMap<>(2);
        List<VueRouter<Menu>> userRouters = this.baseService.getUserRouters(username);
        String userPermissions = this.baseService.findUserPermissions(username);
        String[] permissionArray = new String[0];
        if (StringUtils.isNoneBlank(userPermissions)) {
            permissionArray = StringUtils.splitByWholeSeparatorPreserveAllTokens(userPermissions, CnswhyConstant.COMMA);
        }
        result.put("routes", userRouters);
        result.put("permissions", permissionArray);
        return R.success(result);
    }

    @GetMapping
    public R<Object> menuList(Menu menu) {
        Map<String, Object> menus = this.baseService.findMenus(menu);
        return success(menus);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<Menu> menuList = list.stream().map((map) -> {
            Menu menu = Menu.builder().build();
            //TODO 请在这里完成转换
            return menu;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(menuList));
    }
}
